<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CaiNiaoController extends Controller
{
    // 序列号商品 itemId ==> 716515621,  SKU/保质期 itemId => 35343434
    protected $itemId = "716515621";

    // 序列号商品 itemCode => SKUB00001, SKU itemCode => SKUA00001， 保质期 itemCode => SKUC00001
    protected $itemCode = "SKUB00001";

    // 库房编码
    protected $storeCode = "20210425CAINIAO";

    // 库存类型: 1-可销售库存, 101-残次品
    // 良品库存类型
    protected $normalInventoryType = 1;
    // 残次库存类型
    protected $defInventoryType = 101;

    protected $normalQuantity = 3;

    protected $defQuantity = 9;

    public function index(Request $request)
    {
        $method = $request->get('method');
        if (empty($method)) {
            return [];
        }
        $method = str_replace('.', '_', $method);

        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }

        return $this->$method($request);
    }

    // 获取销退收货信息（taobao.wlb.wms.return.bill.get）
    public function taobao_wlb_wms_return_bill_get(Request $request)
    {
        $orderType = 501;
        $inventoryItem = [
            "inventory_item" => [
                "inventory_type" => $this->normalInventoryType,
                "item_qty" => $this->normalQuantity,
                "produce_code" => rand(0000, 9999),
                "produce_area" => "浙江杭州",
                "batch_code" => Str::random(10)
            ]
        ];
        if ($this->itemCode == "SKUC00001") {
            $inventoryItem['inventory_item']['produce_date'] = date("Y-m-d H:i:s", strtotime("-1 week"));
        }

        $inventoryItem2 = $inventoryItem;
        $inventoryItem2['inventory_item']['item_qty'] = $this->defQuantity;
        $inventoryItem2['inventory_item']['inventory_type'] = $this->defInventoryType;
        if ($this->itemCode == "SKUC00001") {
            $inventoryItem2['inventory_item']['produce_date'] = date("Y-m-d H:i:s", strtotime("-2 week"));
        }

        $orderItem = [
            "order_item" => [
                "order_item_id" => "3424",
                "item_id" => $this->itemId,
                "item_code" => $this->itemCode,
                "inventory_item_list" => [
                    "cainiao_return_bill_inventoryitemlist" => [
                        $inventoryItem, $inventoryItem2
                    ]
                ]
            ]
        ];

        return [
            "wlb_wms_return_bill_get_response" => [
                "return_order_info" => [
                    "order_code" => sprintf('ERP%s', date("YmdHis")),
                    "cn_order_code" => sprintf('LBX%s%s', date("YmdHis"), Str::random("3")),
                    "order_type" => $orderType,
                    "confirm_time" => date("Y-m-d H:i:s"),
                    "order_item_list" => [
                        "cainiao_return_bill_orderitemlist" => [
                            $orderItem
                        ]
                    ],
                    "pre_cn_order_code" => sprintf('LBX%s%s', date("YmdHis"), Str::random("6"))
                ],
            ],
        ];
    }

    public function buildInventoryItemList()
    {
        $inventoryitemlists = [];
        for ($i = 1; $i <= $this->normalQuantity; $i++) {
            $inventoryitemlist = [
                'inventory_item' => [
                    "batch_code" => "520000114972442",
                    "inventory_type" => $this->normalInventoryType,
                    "item_qty" => 1,
                    "produce_code" => "-",
                ]
            ];

            if ($this->itemCode == "SKUC00001") {
                $produceDate = date("Y-m-d H:i:s", strtotime(sprintf("-%s day", rand(0, 4))));
                $inventoryitemlist['inventory_item']['produce_date'] = $produceDate;
            }

            $inventoryitemlists[] = $inventoryitemlist;
        }

        for ($i = 1; $i <= $this->defQuantity; $i++) {
            $inventoryitemlist = [
                'inventory_item' => [
                    "batch_code" => "520000114972442",
                    "inventory_type" => $this->defInventoryType,
                    "item_qty" => 1,
                    "produce_code" => "-",
                ]
            ];

            if ($this->itemCode == "SKUC00001") {
                $produceDate = date("Y-m-d H:i:s", strtotime(sprintf("-%s day", rand(0, 5))));
                $inventoryitemlist['inventory_item']['produce_date'] = $produceDate;
            }

            $inventoryitemlists[] = $inventoryitemlist;
        }

        return $inventoryitemlists;
    }

    // 获取销售订单发货信息（taobao.wlb.wms.consign.bill.get）
    public function taobao_wlb_wms_consign_bill_get(Request $request)
    {
        $status = 'WMS_CONFIRMED';
        $orderCode = $request->get('order_code', '');
        $cnOrderCode = $request->get('cn_order_code', '');

        $orderitemlist = [
            'order_item' => [
                "item_code" => $this->itemCode,
                "item_id" => $this->itemId . Str::random(5),
                "order_item_id" => "523097678376",
                "order_source_code" => !empty($orderCode) ? $orderCode : '3199002375453282541',
                "inventory_item_list" => [
                    'inventoryitemlist' => $this->buildInventoryItemList()
                ],
            ],
        ];

        $tmsitemlist = [
            'tms_item' => [
                "item_qty" => 1,
                "item_code" => $this->itemCode,
                "item_id" => $this->itemId . Str::random(5),
            ]
        ];

        $tmsorderlist = [
            'tms_order' => [
                "tms_code" => "ZTO",
                "tms_order_code" => sprintf("ZTO%s", $this->getDateTime(Str::random(1))),
                "package_code" => sprintf('package_code_%s', Str::random(6)),
                "package_height" => 74,
                "package_length" => 193,
                "package_material_list" => [],
                "package_weight" => 145,
                "package_width" => 135,
                "tms_item_list" => [
                    'tmsitemlist' => [
                        $tmsitemlist, $tmsitemlist
                    ]
                ],
            ]
        ];

        $tmsorderlist2 = [
            'tms_order' => [
                "tms_code" => "SF",
                "tms_order_code" => sprintf("SF%s", $this->getDateTime(Str::random(1))),
                "package_code" => sprintf('package_code_%s', Str::random(6)),
                "package_height" => 74,
                "package_length" => 193,
                "package_material_list" => [],
                "package_weight" => 145,
                "package_width" => 135,
                "tms_item_list" => [
                    'tmsitemlist' => [
                        $tmsitemlist, $tmsitemlist, $tmsitemlist, $tmsitemlist
                    ]
                ],
            ]
        ];

        $tmsorderlist3 = [
            'tms_order' => [
                "tms_code" => "DBKD",
                "tms_order_code" => sprintf("DBKD%s", $this->getDateTime(Str::random(1))),
                "package_code" => sprintf('package_code_%s', Str::random(6)),
                "package_height" => 74,
                "package_length" => 193,
                "package_material_list" => [],
                "package_weight" => 145,
                "package_width" => 135,
                "tms_item_list" => [
                    'tmsitemlist' => [
                        $tmsitemlist, $tmsitemlist, $tmsitemlist, $tmsitemlist
                    ]
                ],
            ]
        ];

        $tmsorderlist4 = [
            'tms_order' => [
                "tms_code" => "YUNDA",
                "tms_order_code" => sprintf("YUNDA%s", $this->getDateTime(Str::random(1))),
                "package_code" => sprintf('package_code_%s', Str::random(6)),
                "package_height" => 74,
                "package_length" => 193,
                "package_material_list" => [],
                "package_weight" => 145,
                "package_width" => 135,
                "tms_item_list" => [
                    'tmsitemlist' => [
                        $tmsitemlist, $tmsitemlist
                    ]
                ],
            ]
        ];

        return [
            'wlb_wms_consign_bill_get_response' => [
                'consign_send_info_list' => [
                    'consignsendinfolist' => [
                        [
                            'consign_send_info' => [
                                "status" => $status,
                                "store_code" => $this->storeCode,
                                "cn_order_code" => $cnOrderCode ?? sprintf("LBX%s%s", date('YmdHis'), Str::random(6)),
                                "confirm_time" => date('Y-m-d H:i:s'),
                                "order_code" => "BMC20230130506362359821",
                                "order_item_list" => [
                                    'orderitemlist' => [$orderitemlist],
                                ],
                                "tms_order_list" => [
                                    'tmsorderlist' => [
                                        $tmsorderlist, $tmsorderlist2, $tmsorderlist3, $tmsorderlist4
                                    ],
                                ],
                            ],
                        ]
                    ]
                ],
                'request_id' => Str::random(10),
            ],
        ];
    }

    // 商家按照仓的类型获取仓库接口 (taobao.wlb.stores.baseinfo.get)
    public function taobao_wlb_stores_baseinfo_get()
    {
        $storeInfo = [
            "real_name" => "XXX果园1",
            "name" => "XXX果园",
            "service_code" => "WHU204",
            "address" => "浙江省杭州市西湖区网商路699号"
        ];

        return [
            'wlb_stores_baseinfo_get_response' => [
                "store_info_list" => [
                    "store_info" => [$storeInfo]
                ],
                "total_count" => 100
            ]
        ];
    }

    // 查询单据序列号信息（taobao.wlb.wms.sn.info.query）
    public function taobao_wlb_wms_sn_info_query()
    {
        $sninfolist = [];
        for ($i = 1; $i <= $this->normalQuantity; $i++) {
            $sninfolist[] = $this->_getNormalSns();
        }
        for ($i = 1; $i <= $this->defQuantity; $i++) {
            $sninfolist[] = $this->_getDefSns();
        }

        return [
            'wlb_wms_sn_info_query_response' => [
                'result' => [
                    "success" => true,
                    "error_code" => "0",
                    "error_msg" => "",
                    "total_count" => $this->normalQuantity + $this->defQuantity,
                    "sn_info_list" => [
                        'sninfolist' => $sninfolist
                    ]
                ],
            ],
        ];
    }

    // 良品序列号
    private function _getNormalSns()
    {
        return [
            'sn_info' => [
                "inventory_type" => $this->normalInventoryType,
                "sn_code" => $this->getDateTime(rand(1000, 9999) . Str::random(3)),
                "item_code" => "SKUB00001",
                "item_id" => "716515621"
            ]
        ];
    }

    // 残次序列号
    public function _getDefSns()
    {
        return [
            'sn_info' => [
                "inventory_type" => $this->defInventoryType,
                "sn_code" => $this->getDateTime('0000' . Str::random(3)),
                "item_code" => "SKUB00001",
                "item_id" => "716515621"
            ]
        ];
    }

    // 查询单据列表（taobao.wlb.wms.cainiao.bill.query）
    public function taobao_wlb_wms_cainiao_bill_query()
    {
        $status = 'WMS_CONFIRMED';
        $order_info = [
            'order_info' => [
                "remark" => "备注",
                "modified_time" => date("Y-m-d H:i:s"),
                "status" => $status,
                "store_code" => $this->storeCode,
                "order_type" => 201,
                "order_code" => "23333",
                "cn_order_code" => sprintf("LBX%s", $this->getDateTime(Str::random(3))),
                "order_source" => "201",
                "order_source_codes" => [
                    '3199002375453282541'
                ]
            ]
        ];

        return [
            'wlb_wms_cainiao_bill_query_response' => [
                'order_info_list' => [
                    'cainiao_bill_query_orderinfolist' => [
                        $order_info
                    ]
                ],
                'total_count' => 11,
            ]
        ];
    }

    // 通过订单号获取单个出库单发货信息 (taobao.wlb.wms.stock.out.bill.get)
    public function taobao_wlb_wms_stock_out_bill_get(Request $request)
    {
        $cn_order_code = $request->get('cn_order_code', '');
        $orderItemId = '37920';

        $package_items = [
            "package_item" => [
                "order_item_id" => $orderItemId,
                "item_id" => $this->itemId,
                "item_code" => $this->itemCode,
                "inventory_type" => $this->normalInventoryType,
                "item_qty" => $this->normalQuantity
            ]
        ];

        $package_items2 = $package_items;
        $package_items2['package_item']['item_qty'] = $this->defQuantity;
        $package_items2['package_item']['inventory_type'] = $this->defInventoryType;

        $package_infos = [
            "package_info" => [
                "tms_code" => "ZTO",
                "tms_order_code" => sprintf("ZTO%s", $this->getDateTime(Str::random(3))),
                "package_code" => "4343435352",
                "package_weight" => 1231,
                "package_length" => 2321,
                "package_width" => 3421,
                "package_height" => 1221,
                "package_item_list" => [
                    "cainiao_stock_out_bill_packageitemlist" => [
                        $package_items
                    ]
                ]
            ],
        ];

        $package_infos2 = [
            "package_info" => [
                "tms_code" => "SF",
                "tms_order_code" => sprintf("SF%s", $this->getDateTime(Str::random(3))),
                "package_code" => "4343435352",
                "package_weight" => 1231,
                "package_length" => 2321,
                "package_width" => 3421,
                "package_height" => 1221,
                "package_item_list" => [
                    "cainiao_stock_out_bill_packageitemlist" => [
                        $package_items2
                    ]
                ]
            ],
        ];

        $inventory_items = [
            "inventory_item" => [
                "inventory_type" => $this->normalInventoryType,
                "item_qty" => $this->normalQuantity,
                "produce_code" => "44566",
                "produce_area" => "浙江杭州",
                "batch_code" => "113344"
            ],
        ];

        if ($this->itemCode == "SKUC00001") {
            $inventory_items['inventory_item']['produce_date'] = "2015-08-20 13:36:26";
        }

        $inventory_items2 = $inventory_items;
        $inventory_items2['inventory_item']['inventory_type'] = $this->defInventoryType;
        $inventory_items2['inventory_item']['item_qty'] = $this->defQuantity;
        if ($this->itemCode == "SKUC00001") {
            $inventory_items2['inventory_item']['produce_date'] = date("Y-m-d H:i:s", strtotime("-1 week"));
        }

        $order_items = [
            "order_item" => [
                "order_item_id" => $orderItemId,
                "item_id" => $this->itemId,
                "item_code" => $this->itemCode,
                "apply_qty" => $this->normalQuantity + $this->defQuantity,
                "inventory_item_list" => [
                    "cainiao_stock_out_bill_inventoryitemlist" => [
                        $inventory_items,
                        $inventory_items2
                    ],
                ]
            ],
        ];

        return [
            "wlb_wms_stock_out_bill_get_response" => [
                "stock_out_info" => [
                    "order_code" => "223332",
                    "cn_order_code" => $cn_order_code,
                    "order_type" => 903,
                    "confirm_time" => $this->getDateTime(),
                    "status" => "ACCEPT",
                    "package_info_list" => [
                        "cainiao_stock_out_bill_packageinfolist" => [
                            $package_infos, $package_infos2
                        ],
                    ],
                    "order_item_list" => [
                        "cainiao_stock_out_bill_orderitemlist" => [
                            $order_items
                        ]
                    ]
                ],
            ],
        ];
    }

    protected function getDateTime($str = '')
    {
        return !empty($str) ? date("YmdHis") . $str : date("Y-m-d H:i:s");
    }
}
